/**
 * @Description: 广告[banner]
 * @author ln
 * @date 2019-04-24 16:53:07
 */
import React, { Fragment } from 'react';
import BraftEditor from 'braft-editor';
import Modal from 'drag-modal';
import moment from 'moment';
import {
  BackTop,
  Button,
  Card,
  Checkbox,
  Col, DatePicker,
  Divider,
  Form,
  Icon,
  Input,
  Radio,
  Row,
  Select,
  Spin,
  Table, Tag,
  Tooltip,
  Upload,
} from 'antd';
import { formatMessage, FormattedMessage } from 'umi/locale';
import 'antd/dist/antd.css';
import PropTypes from 'prop-types';
import { connect } from 'dva';
import { requestLists, requestPromise } from '@/utils/request';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import BaseForm from '../../../components/ourslook/BaseForm';
import ETable from '../../../components/ourslook/ETable';
import { getWebPath } from '../../../utils/request';
import uiUtils, { hasPermission, rulesReg } from '../../../utils/uiUtils';
import styles from '../../../utils/ourslook.less';
import 'braft-editor/dist/index.css';
import { handleEditorupload , editorPreview, editorProps} from '../../../utils/braft_editor_config';
import DefaultImage from '../../../components/ourslook/DefaultImage';

const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
const TextArea = Input.TextArea;
const Password = Input.Password;
const CheckboxGroup = Checkbox.Group;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

@connect(() => ({}))
class InfAdvertise extends React.Component {
  params = {
    page: 1,
    limit: 10,
  };

  formItemLayout = {
    labelCol: { span: 5 },
    wrapperCol: { span: 19 },
  };

  /**
   * https://ant-design.gitee.io/components/table-cn/
   *
   * 需要指定 column 的 width 属性，否则列头和内容可能不对齐。（必须留一列不设宽度或者minWidth以适应弹性布局）
   * 建议指定 scroll.x 为大于表格宽度的固定值或百分比。注意，且非固定列宽度之和不要超过 scroll.x, 一般无table正常展开的宽度
   * 未知长度字段或者字符特别多的字段不要放置在列表
   */
  columns = [
    {
      title: '',
      width: 30,
      align: 'center',
      fixed: 'left',
      render: (value, record, index) => index + 1,
    },
    { title: '标题', dataIndex: 'adTitle', width: 190, align: 'center', sorter: false },
    { title: '广告类型', dataIndex: 'advertiseTypeName', align: 'center', sorter: false },
    {
      title: '广告图片',
      dataIndex: 'adImg',
      width: 100,
      align: 'center',
      sorter: false,
      render: record => <DefaultImage src={record} width="80" />,
    },
    {
      title: '创建时间',
      dataIndex: 'createTime',
      width: 160,
      align: 'center',
      sorter: true,
      key: 'create_time',
    },
    { title: '排序', dataIndex: 'sort', width: 100, align: 'center', sorter: true },
    {
      title: '状态',
      dataIndex: 'status',
      width: 120,
      align: 'center',
      sorter: false,
      render: (value, record, index) =>
        value === 0 ? (
          <Tag style={{ cursor: 'default' }} className={styles.label_success}>
            自定义上架时间
          </Tag>
        ) : value === 1 ? (
          <Tag style={{ cursor: 'default' }} className={styles.label_danger}>
            下架
          </Tag>
        ) : (
          <Tag style={{ cursor: 'default' }} className={styles.label_primary}>
            上架
          </Tag>
        )
    },
    {
      title: '操作',
      dataIndex: '',
      width: 120,
      align: 'center',
      fixed: 'right',
      render: (value, record, index) => (
        <React.Fragment>
          <a
            hidden={!hasPermission('infAdvertise:update')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.update();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />}>
              <Icon type="edit" />
            </Tooltip>
          </a>
          <Divider type="vertical" />
          <a
            hidden={!hasPermission('infAdvertise:info')}
            onClick={() => {
              this.setStateByTableColume(record, index);
              this.view();
            }}
          >
            <Tooltip title={<FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />}>
              <Icon type="info" />
            </Tooltip>
          </a>
        </React.Fragment>
      ),
    },
  ];

  constructor(props) {
    super(props);
    this.state = {
      showList: 1, //1:显示列表、2:显示新增
      formList: InfAdvertise.getFormList(),
      selectedRows: [],
      selectedIds: [],
      selectedIndexs: [],
      editModalTitle: null,
      editModalType: null,
      editModel: null,
      editModelConfirmLoading: false,
      //其他属性下面书写
      adTypeList: [],
      contentHtml: BraftEditor.createEditorState(''),
      jumpList: [],
    };
  }

  // 筛选条件
  static getFormList = () => [
    {
      type: 'INPUT',
      field: 'adTitle',
      label: '标题',
      placeholder: '标题',
    },
    {
      type: 'SELECT',
      field: 'adType',
      label: '广告类型',
      placeholder: '广告类型',
      list: [{ id: '', name: '请选择广告类型' }],
    },
    {
      type: 'SELECT',
      field: 'status',
      label: '状态',
      placeholder: '状态',
      list: [{ id: '', name: '请选择状态' }],
    },
  ];

  componentDidMount() {
    this.params.order = 'desc';
    this.params.sidx = 'sort';
    this.requestList();
    this.getAdTypeList();
    this.getJumpList();
    this.getStatusList();
  }

  /**
   * 根据 formItem field 取值 查找formItem
   * @param formItemField obj的field字段
   * @returns 一个对象
   */
  findFormListItemByField = formItemField =>
    this.state.formList.find((value, index, array) => value.field === formItemField);

  query = fieldParams => {
    this.params.order = 'desc';
    this.params.sidx = 'sort';
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, fieldParams)));
    this.requestList();
  };

  getJumpList = () => {
    requestPromise(`${getWebPath('/api/constants?type=JumpType')}`, {
      method: 'GET',
    }).then(res => {
      if (res) {
        const jump = uiUtils.getOptionJsonObjToArr(res.JumpType);
        const intNewJumpArr = [{ id: '', name: '请选择跳转类型' }];
        jump.forEach(item => {
          if (item.id !== '') {
            intNewJumpArr.push({ id: Number.parseFloat(item.id), name: item.name });
          }
        });
        this.setState({
          jumpList: intNewJumpArr,
        });
      }
    });
  };

  getStatusList = () => {
    const newStatus = [
      { id: '', name: '请选择状态' },
      { id: '2', name: '上架' },
      { id: '0', name: '自定义上架时间' },
      { id: '1', name: '下架' },
    ];
    const formItem = this.findFormListItemByField('status');
    formItem.list = newStatus;
  };

  setStateByTableColume = (record, index) => {
    this.state = {
      ...this.state,
      selectedRows: [record],
      selectedIds: [record.id],
      selectedIndexs: [index],
    };
  };

  add = () => {
    this.setState({
      editModalType: 'add',
      editModalTitle: formatMessage({ id: 'ours.curd.list.create' }), //创建
      editModel: {
        jumpType: '',
        adType: '',
        sort: 0,
        status: 2,
      },
      showList: 2,
      contentHtml: BraftEditor.createEditorState(''),
    });
  };

  update = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    selectedRows[0].sort = `${selectedRows[0].sort}`;
    this.setState({
      editModalType: 'update',
      editModalTitle: <FormattedMessage id="ours.curd.list.edit" defaultMessage="编辑" />,
      editModel: selectedRows[0],
      showList: 2,
      contentHtml: BraftEditor.createEditorState(selectedRows[0].content),
    });
    this.getInfo(selectedRows[0].adId);
  };

  getInfo = adId => {
    this.setState({
      editModelConfirmLoading: true,
    });
    requestPromise(`${getWebPath(`/infAdvertise/infoVo/${adId}`)}`, {
      method: 'GET',
    }).then(res => {
      this.setState({
        editModelConfirmLoading: false,
      });
      if (res && res.code === 0) {
        const jumpType = res.infAdvertiseVo.jumpType;
        const jumpUrl = res.infAdvertiseVo.jumpUrl;
        this.editForm.getSelectUser(jumpType);
        this.editForm.props.model.jumpUrlName = res.infAdvertiseVo.jumpUrlName;

        if (
          jumpType === 2 ||
          jumpType === 3 ||
          jumpType === 4 ||
          jumpType === 5 ||
          jumpType === 6
        ) {
          const selectedRowKeys = [];
          // eslint-disable-next-line radix
          selectedRowKeys.push(Number.parseInt(jumpUrl));
          this.editForm.setState({
            selectedRowKeys,
          });
        }
      }
    });
  };

  view = () => {
    const { selectedRows, selectedIds, selectedIndexs } = this.state;
    if (!selectedRows) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-please' }));
      return;
    }
    if (selectedRows.length > 1) {
      uiUtils.showAlert(formatMessage({ id: 'ours.curd.show-alert.select-one-please' }));
      return;
    }
    this.setState({
      editModalType: 'view',
      editModalTitle: <FormattedMessage id="ours.curd.list.info" defaultMessage="查看" />,
      editModel: selectedRows[0],
      showList: 2,
      contentHtml: BraftEditor.createEditorState(selectedRows[0].content),
    });
    this.getInfo(selectedRows[0].adId);
  };

  del = () => {
    const selectedRows = this.state.selectedRows;
    const adIds = [];
    for (let i = 0; i < selectedRows.length; i += 1) {
      adIds.push(selectedRows[i].adId);
    }

    uiUtils.showConfirm(formatMessage({ id: 'ours.curd.show-alert.confirm-delete' }), () => {
      this.setState({
        loading: true,
      });
      requestPromise(`${getWebPath('/infAdvertise/delete')}`, {
        method: 'DELETE',
        body: adIds,
      }).then(res => {
        this.setState({
          loading: false,
        });
        if (res && JSON.parse(res).code === 0) {
          uiUtils.showMessage(
            formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
            'success'
          );
          this.requestList();
        }
      });
    });
  };

  saveOrUpdate = () => {
    const editModalType = this.state.editModalType;
    //不能双向绑定，这里只能原对象、新对象进行合并.
    const infAdvertise = Object.assign(
      this.state.editModel,
      this.editForm.props.form.getFieldsValue()
    );

    if (infAdvertise.jumpType === -1) {
      infAdvertise.content = infAdvertise.content.toHTML();
    }

    if (infAdvertise.shelvesTime !== undefined && infAdvertise.status === 0) {
      infAdvertise.shelvesTime = `${infAdvertise.shelvesTime.format('YYYY-MM-DD HH:mm:ss')}`;
    }

    this.editForm.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        // submit the values
        const url = infAdvertise.adId == null ? '/infAdvertise/save' : '/infAdvertise/update';
        //对象删除一个属性
        //delete infAdvertise.xxxxPros;

        this.setState({
          editModelConfirmLoading: true,
        });
        requestPromise(`${getWebPath(url)}`, {
          method: 'POST',
          body: infAdvertise,
        }).then(res => {
          this.setState({
            editModelConfirmLoading: false,
          });
          if (res && res.code === 0) {
            uiUtils.showMessage(
              formatMessage({ id: 'ours.curd.show-alert.operate-success' }),
              'success'
            );
            this.setState({
              showList: 1,
              list: [],
            });

            //新增重新置为第一页
            if (!infAdvertise.adId) {
              this.params.page = 1;
            }
            this.requestList();
          }
        });
      }
    });
  };

  //========其他所有的处理方法，请在按照约定进行处理==========

  /**
   * 表格 筛选和排序 回调
   */
  filtersSorterChange = tableParams => {
    this.params = JSON.parse(JSON.stringify(Object.assign(this.params, tableParams)));
    this.requestList();
  };

  requestList = () => {
    requestLists(this, `${getWebPath('/infAdvertise/list')}`, this.params);
  };

  getAdTypeList = () => {
    requestPromise(`${getWebPath('/dictInfo/list?type=TYPE_BANNER_ADVERTISING')}`, {
      method: 'GET',
    }).then(res => {
      if (res && res.code === 0) {
        const adTypes = res.page.list || [];
        const newAdTypes = [
          { id: '', name: '请选择广告类型' },
          ...adTypes.map(e => ({ id: e.code, name: e.name })),
        ];

        const { formList: formListNew } = this.state;
        const formItem = this.findFormListItemByField('adType');
        formItem.list = newAdTypes;
        this.setState({
          formList: formListNew,
          adTypeList: newAdTypes,
        });
      }
    });
  };

  vShow = showListNum => ({ display: this.state.showList === showListNum ? 'block' : 'none' });

  render() {
    const style = {
      style: {
        marginLeft: 10,
        marginTop: 10,
      },
      disabled: this.state.selectedIndexs.length <= 0,
    };

    /* eslint-disable react/jsx-no-bind */
    return (
      <PageHeaderWrapper title="">
        <Card
          bordered={false}
          style={{ ...this.vShow(1) }}
          className={styles.oursCard}
          bodyStyle={{ padding: '20px' }}
        >
          <BaseForm
            formList={this.state.formList}
            loading={this.state.loading}
            filterSubmit={this.query}
          />

          <Fragment>
            <Button
              type="primary"
              icon="plus"
              onClick={this.add}
              hidden={!hasPermission('infAdvertise:save')}
            >
              <FormattedMessage id="ours.curd.list.add" defaultMessage="新增" />
            </Button>
            <Button
              type="danger"
              icon="delete"
              {...style}
              onClick={this.del}
              hidden={!hasPermission('infAdvertise:delete')}
            >
              <FormattedMessage id="ours.curd.list.delete" defaultMessage="删除" />
            </Button>
          </Fragment>

          <div className="content-wrap">
            <ETable
              onSelectRow={uiUtils.onSelectRow.bind(this)}
              primaryKey="adId"
              selectedIndexs={this.state.selectedIndexs}
              selectedRows={this.state.selectedRows}
              selectedIds={this.state.selectedIds}
              onChange={this.filtersSorterChange}
              columns={this.columns}
              dataSource={this.state.list}
              pagination={this.state.pagination}
              loading={this.state.loading}
              scroll={{ x: 900 }}
            />
          </div>
        </Card>

        <BackTop />

        <Spin spinning={this.state.editModelConfirmLoading} delay={10}>
          {//返回null,这里对不用的组件进行销毁
          this.state.showList === 1 ? null : (
            <Card
              title={this.state.editModalTitle}
              bordered={false}
              actions={[
                <div>
                  <React.Fragment>
                    <Button
                      type="primary"
                      hidden={this.state.editModalType === 'view'}
                      style={{ marginRight: '18px' }}
                      onClick={this.saveOrUpdate}
                    >
                      <FormattedMessage id="ours.curd.add.save" defaultMessage="保存" />
                    </Button>
                    <Button
                      style={{ marginRight: '18px' }}
                      onClick={() => {
                        this.editForm.props.form.resetFields();
                        this.setState({ showList: 1 });
                      }}
                    >
                      <FormattedMessage id="ours.curd.add.back" defaultMessage="返回" />
                    </Button>
                  </React.Fragment>
                </div>,
              ]}
              style={{ ...this.vShow(2) }}
              bodyStyle={{ padding: '20px' }}
              ref={node => {
                this.container = node;
              }}
            >
              <EditForm
                type={this.state.editModalType}
                model={this.state.editModel}
                adTypeList={this.state.adTypeList}
                contentHtml={this.state.contentHtml}
                jumpList={this.state.jumpList}
                wrappedComponentRef={inst => {
                  this.editForm = inst;
                }}
              />
            </Card>
          )}
        </Spin>
      </PageHeaderWrapper>
    );
  }
}

export default InfAdvertise;

/**
 *  新增、编辑、复制、查看的Form
 */

/* eslint react/no-multi-comp:0 */
class EditForm extends React.Component {
  static propTypes = {
    type: PropTypes.string, //form类型，可选值：add（增加）、update（修改）、copy（复制）、view（查看）、
    model: PropTypes.object, //数据模型model，对应后台的model
    adTypeList: PropTypes.object,
    contentHtml: PropTypes.object,
    jumpList: PropTypes.object,
  };

  static defaultProps = {
    type: '', //表单布局数组
    model: null,
    adTypeList: [],
    contentHtml: BraftEditor.createEditorState(''),
    jumpList: [],
  };

  constructor(props) {
    super(props);
    const defaultFileList = this.props.model.adImg
      ? [
          {
            uid: '1',
            name: '',
            status: 'done',
            url: this.props.model.adImg,
            type: 'image/',
          },
        ]
      : null; //defaultFileList

    this.state = {
      isShowUser: false,
      previewVisible: false, //上传文件预览
      previewImage: '', //上传文件预览
      defaultFileList, //上传文件列表
      fileList: defaultFileList && defaultFileList.length > 0 ? [defaultFileList[0]] : [],
      allUserColumns: [
        {
          title: 'id',
          dataIndex: 'id',
          key: 'id',
        },
        {
          title: '名称',
          dataIndex: 'name',
          key: 'name',
        },
      ],
      likeProductName:null
    };
  }

  /**
   * 生命周期-属性发生变化...componentWillReceiveProps
   * 这里的nextProps，可以获取到所有的属性。
   * 目前没用，因为 dialog 每次都被销毁了
   */
  componentWillReceiveProps(nextProps) {}

  getPropsByKey = prop => {
    const model = this.props.model || {};
    const finalModel = Object.assign(model, this.props.form.getFieldsValue());
    return finalModel[prop];
  };

  handleUploadPreview = file => {
    const previewImage = file.url || file.thumbUrl;
    const previewVisible = file.type.startsWith('image/');
    this.setState({
      previewImage,
      previewVisible,
    });
  };

  handleUploadOnRemove = file => {
    //只上传一文件，这里偷懒
    this.setState({
      fileList: [],
      defaultFileList: null,
    });
  };

  handleUploadOnChange = info => {
    const { loadingCallback } = this.props;
    // 状态有：uploading done error removed
    if (info.file.status === 'done') {
      //这个Upload组件比较特殊，这里在OnChange方法手工设置value,不做延迟，就设置不了被覆盖了。
      const response = info.fileList[0].response;
      this.setState({
        fileList: info.fileList,
      });
      if (response) {
        if (response.code === 0) {
          uiUtils.showMessage(`${info.file.name} 文件上传成功.`, 'success');
          setTimeout(() => {
            this.props.form.setFieldsValue({
              adImg: response.object,
            });
            if (loadingCallback) {
              loadingCallback(false);
            }
          }, 500);
        } else {
          uiUtils.showAlert(response.msg, 'error');
          if (loadingCallback) {
            loadingCallback(false);
          }
        }
      }
    } else if (info.file.status === 'error') {
      if (loadingCallback) {
        loadingCallback(false);
      }
      uiUtils.showMessage(`${info.file.name} 文件上传失败.`, 'error');
    } else if (info.file.status === 'uploading') {
      if (loadingCallback) {
        loadingCallback(true);
      }
    }
  };

  preview = () => {
    editorPreview(this.state.editorState.toHTML());
  };

  getSelectUser = (value,likeProductName) => {
    if (value === 2) {
      //杂志订阅
      const params = {
        order: 'desc',
        sidx: 'sort',
        status: 2,
        productName:likeProductName
      };
      requestPromise(`${getWebPath(`/mailproduct/list`)}`, {
        method: 'POST',
        contentType: 'application/x-www-form-urlencoded',
        body: params,
      }).then(res => {
        if (res && res.code === 0) {
          const userInfo = res.page.list || [];
          const intNewUserInfoArr = [];
          userInfo.forEach(item => {
            intNewUserInfoArr.push({ key: item.id, id: item.id, name: item.productName });
          });
          this.setState({
            allUserList: intNewUserInfoArr,
          });
        }
      });
    } else if (value === 3) {
      //专题活动
      const params = {
        status: 1,
        between_startTime_endTime: '1',
        topicName:likeProductName
      };
      requestPromise(`${getWebPath(`/promotiontopic/list`)}`, {
        method: 'POST',
        contentType: 'application/x-www-form-urlencoded',
        body: params,
      }).then(res => {
        if (res && res.code === 0) {
          const userInfo = res.page.list || [];
          const intNewUserInfoArr = [];
          userInfo.forEach(item => {
            intNewUserInfoArr.push({ key: item.topicId, id: item.topicId, name: item.topicName });
          });
          this.setState({
            allUserList: intNewUserInfoArr,
          });
        }
      });
    } else if (value === 4) {
      //推荐有礼
      const params = {
        status: 1,
        between_startTime_endTime: '1',
        recommendName:likeProductName
      };
      requestPromise(`${getWebPath(`/promotionrecommend/list`)}`, {
        method: 'POST',
        contentType: 'application/x-www-form-urlencoded',
        body: params,
      }).then(res => {
        if (res && res.code === 0) {
          const userInfo = res.page.list || [];
          const intNewUserInfoArr = [];
          userInfo.forEach(item => {
            intNewUserInfoArr.push({
              key: item.recommendId,
              id: item.recommendId,
              name: item.recommendName,
            });
          });
          this.setState({
            allUserList: intNewUserInfoArr,
          });
        }
      });
    } else if (value === 5) {
      //拼团活动
      const params = {
        between_startTime_endTime: '1',
        title:likeProductName
      };
      requestPromise(`${getWebPath(`/promotiongroupon/list`)}`, {
        method: 'POST',
        contentType: 'application/x-www-form-urlencoded',
        body: params,
      }).then(res => {
        if (res && res.code === 0) {
          const userInfo = res.page.list || [];
          const intNewUserInfoArr = [];
          userInfo.forEach(item => {
            intNewUserInfoArr.push({ key: item.productId, id: item.productId, name: item.title });
          });
          this.setState({
            allUserList: intNewUserInfoArr,
          });
        }
      });
    } else if (value === 6) {
      //免费试读
      const params = {
        productName:likeProductName
      };
      requestPromise(`${getWebPath(`/promotiontryout/listVo`)}`, {
        method: 'POST',
        contentType: 'application/x-www-form-urlencoded',
        body: params,
      }).then(res => {
        if (res && res.code === 0) {
          const userInfo = res.page.list || [];
          const intNewUserInfoArr = [];
          userInfo.forEach(item => {
            intNewUserInfoArr.push({
              key: item.id,
              id: item.id,
              name:
                item.productEntity === null || item.productEntity === undefined
                  ? ''
                  : item.productEntity.productName,
            });
          });
          this.setState({
            allUserList: intNewUserInfoArr,
          });
        }
      });
    }
  };

  selectUser = () => {
    this.setState({ isShowUser: false });
    this.props.model.selectedRowKeys = this.state.selectedRowKeys;
    this.props.model.jumpUrl = this.state.jumpUrl;
    this.props.model.jumpUrlName = this.state.jumpUrlName;
  };

  onSelectChange = (selectedRowKeys, selectedRows) => {
    let jumpUrl = '';
    let jumpUrlName = '';
    for (let i = 0; i < selectedRows.length; i += 1) {
      //jumpUrl += `${selectedRows[i].id},`;
      jumpUrl = selectedRows[i].id;
      jumpUrlName = selectedRows[i].name;
    }
    this.setState({
      jumpUrl,
      jumpUrlName,
      selectedRowKeys,
    });
  };

  getJumTypeName = value => {
    const jumpType = this.props.jumpList.filter((en, index) => en.id === value);
    return jumpType.length > 0 ? jumpType[0].name : '';
  };

  getStatusName = status => {
    let statusName = '';
    if (status === 0) {
      statusName = '自定义上架时间';
    } else if (status === 1) {
      statusName = '下架';
    } else if (status === 2) {
      statusName = '上架';
    }
    return statusName;
  };

  render() {
    const type = this.props.type; //编辑是：新增（add）、编辑(edit)、复制(copy)、还是查看(view)
    const model = this.props.model || {};
    const {
      form,
      form: { getFieldDecorator, getFieldValue, setFieldsValue },
    } = this.props;
    const formItemLayout = {
      labelCol: { span: 5 },
      wrapperCol: { span: 18 }, //5+19=24,少一个栅格
    };
    const braftEditorFormItemLayout = {
      labelCol: { span: 3 },
      wrapperCol: { span: 18 },
    };
    const braftEditorLayout = { md: 30, sm: 20 };
    const colSpanLayout = { md: 12, sm: 24 }; //每一col跨?列
    const rowGutterPxLayout = { md: 24, sm: 16 }; //col之间的间隔?px
    const inputCodeDisabled = {
      disabled: type === 'update',
    };
    const inputCodeDisabledForView = {
      disabled: type === 'view',
    };

    const uploadProps = {
      action: `${getWebPath('/api/fileUpload')}`,
      name: 'myfile',
      data: { moduleName: 'banner', isImage: true, acceptFileExts: 'image' },
      withCredentials: true,
      headers: {
        authorization: 'authorization-text',
      },
      onChange: this.handleUploadOnChange,
      onRemove: this.handleUploadOnRemove,
      defaultFileList: this.state.defaultFileList,
      multiple: false,
      accept: '.jpg, .jpeg, .png, .bmp, ',
    };
    const uploadButton = (
      <div>
        <Icon type="plus" />
        <div className="ant-upload-text">上传</div>
      </div>
    );

    const extendControls = [
      {
        key: 'custom-button',
        type: 'button',
        text: '预览',
        onClick: this.preview,
      },
    ];

    const { selectedRowKeys } = this.state;
    const rowSelection = {
      type: 'radio',
      selectedRowKeys,
      onChange: this.onSelectChange,
    };

    //校验文档：https://ant.design/components/form-cn/#%E6%A0%A1%E9%AA%8C%E8%A7%84%E5%88%99
    return (
      <Form layout="horizontal">
        <Row gutter={{ ...rowGutterPxLayout }}>
          <Col {...colSpanLayout}>
            <FormItem label="标题" {...formItemLayout}>
              {type === 'view'
                ? model.adTitle
                : getFieldDecorator('adTitle', {
                    initialValue: model.adTitle,
                    rules: [
                      {
                        required: true,
                        message: '标题必填',
                      },
                      {
                        max: 200,
                        message: '最长200个字符',
                      },
                    ],
                  })(<Input type="text" autocomplete="off" maxlength={200} placeholder="" />)}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="广告类型" {...formItemLayout}>
              {type === 'view'
                ? model.advertiseTypeName
                : getFieldDecorator('adType', {
                    initialValue: model.adType,
                    rules: [
                      {
                        required: true,
                        message: '广告类型必选',
                      },
                    ],
                  })(
                    <Select style={{ width: '100%' }} placeholder="请选择广告类型">
                      {uiUtils.getOptionList(this.props.adTypeList)}
                    </Select>
                  )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="跳转类型" {...formItemLayout}>
              {type === 'view'
                ? this.getJumTypeName(model.jumpType)
                : getFieldDecorator('jumpType', {
                    initialValue: model.jumpType,
                    rules: [
                      {
                        required: true,
                        message: '跳转类型必选',
                      },
                    ],
                  })(
                    <Select
                      style={{ width: '100%' }}
                      placeholder="请选择跳转类型"
                      onChange={value => {
                        model.jumpType = value;
                        this.props.model.jumpUrl = '';
                        this.props.model.jumpUrlName = '';
                        this.props.model.selectedRowKeys = [];
                        this.setState({
                          selectedRowKeys: [],
                          jumpUrl: '',
                          jumpUrlName: '',
                        });
                      }}
                    >
                      {uiUtils.getOptionList(this.props.jumpList)}
                      {/*<option value={0}>超链接</option>
                      <option value={1}>富文本</option>*/}
                    </Select>
                  )}
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem label="排序" {...formItemLayout}>
              {type === 'view'
                ? model.sort
                : getFieldDecorator('sort', {
                    initialValue: model.sort,
                    rules: [
                      {
                        required: true,
                        message: '排序必填',
                      },
                      rulesReg('plus'),
                    ],
                  })(
                    <Input
                      type="text"
                      autocomplete="off"
                      placeholder="排序"
                      maxLength={9}
                      style={{ width: '94%' }}
                    />
                  )}
              &nbsp;&nbsp;
              <Tooltip placement="right" title="排序默认为从大到小(降序)">
                <Icon type="question-circle" />
              </Tooltip>
            </FormItem>
          </Col>
          <Col {...colSpanLayout}>
            <FormItem
              label="广告图片"
              extra="支持png、jpg、gif, 大小不超过3MB, 推荐尺寸：200X200;"
              {...formItemLayout}
            >
              {getFieldDecorator('adImg', {
                initialValue: model.adImg,
                rules: [
                  {
                    required: true,
                    message: '广告图片必须上传',
                  },
                ],
              })(
                <div className="clearfix">
                  <Upload
                    {...uploadProps}
                    listType="picture-card"
                    onPreview={this.handleUploadPreview}
                  >
                    {this.state.fileList && this.state.fileList.length >= 1 ? null : uploadButton}
                  </Upload>
                  <Modal
                    visible={this.state.previewVisible}
                    footer={null}
                    onCancel={() => this.setState({ previewVisible: false })}
                  >
                    <img alt="imgExample" style={{ width: '100%' }} src={this.state.previewImage} />
                  </Modal>
                </div>
              )}
            </FormItem>
          </Col>
          {(model.jumpType === 2 ||
            model.jumpType === 3 ||
            model.jumpType === 4 ||
            model.jumpType === 5 ||
            model.jumpType === 6) &&
            (type === 'add' || type === 'update') && (
              <Button
                size="small"
                type="primary"
                onClick={() => {
                  this.setState({ isShowUser: true,likeProductName: null,allUserList:[] });
                  this.getSelectUser(model.jumpType);
                }}
              >
                选择数据
              </Button>
            )}
          {model.jumpType === -2 && (
            <Col {...colSpanLayout}>
              <FormItem label="链接地址" {...formItemLayout}>
                {getFieldDecorator('jumpUrl', {
                  initialValue: model.jumpUrl,
                  rules: [
                    {
                      required: true,
                      message: '链接地址必填',
                    },
                    rulesReg('url'),
                  ],
                })(
                  <Input
                    type="text"
                    autocomplete="off"
                    placeholder="链接地址,如：http://www.baidu.com"
                    disabled={type === 'view'}
                  />
                )}
              </FormItem>
            </Col>
          )}
          {(model.jumpType === 2 ||
            model.jumpType === 3 ||
            model.jumpType === 4 ||
            model.jumpType === 5 ||
            model.jumpType === 6) && (
            <Col {...colSpanLayout}>
              <FormItem label="链接地址" {...formItemLayout}>
                {getFieldDecorator('jumpUrlName', {
                  initialValue: model.jumpUrlName,
                  rules: [
                    {
                      required: true,
                      message: '链接地址必填',
                    },
                  ],
                })(<Input type="text" autocomplete="off" disabled />)}
              </FormItem>
            </Col>
          )}
          <Col {...colSpanLayout}>
            <FormItem label="状态" {...formItemLayout}>
              {type === 'view'
                ? this.getStatusName(model.status)
                : getFieldDecorator('status', {
                  initialValue: model.status,
                  rules: [
                    {
                      required: true,
                      message: '状态必选',
                    }
                  ],
                })(
                  <Select
                    style={{ width: '100%' }}
                    onChange={value => {
                      model.status = value;
                    }}
                  >
                    <option value={2}>上架</option>
                    <option value={0}>自定义上架时间</option>
                    <option value={1}>下架</option>
                  </Select>
                )}
            </FormItem>
          </Col>
          {model.status === 0 && (
            <Col {...colSpanLayout}>
              <FormItem label="上架时间" {...formItemLayout}>
                {type === 'view'
                  ? model.shelvesTime
                  : getFieldDecorator('shelvesTime', {
                    initialValue: moment(
                      model.shelvesTime === undefined ? moment() : model.shelvesTime,
                      'YYYY-MM-DD HH:mm:ss'
                    ),
                    rules: [
                      {
                        required: true,
                        message: '上架时间必选',
                      }
                    ],
                  })(
                    <DatePicker
                      showTime
                      placeholder="请选择上架时间"
                      defaultValue={moment(
                        model.shelvesTime === undefined ? moment() : model.shelvesTime,
                        'YYYY-MM-DD HH:mm:ss'
                      )}
                    />
                  )}
              </FormItem>
            </Col>
          )}
        </Row>
        {model.jumpType === -1 && (
          <Card
            bordered
            hoverable
            size="small"
            bodyStyle={{ paddingBottom: 10 }}
            style={{ marginBottom: 20 }}
            title="广告内容"
          >
            {getFieldDecorator('content', {
              initialValue: BraftEditor.createEditorState(model.content),
            })(
              <BraftEditor
                className={styles.my_editor}
                placeholder="请输入广告内容"
                onChange={editorState => {
                  // eslint-disable-next-line react/no-unused-state
                  this.setState({ editorState });
                }}
                extendControls={extendControls}
                {...inputCodeDisabledForView}
                {...editorProps}
              />
            )}
          </Card>
        )}
        <Modal
          width={700}
          height={500}
          visible={this.state.isShowUser}
          title="选择数据"
          onCancel={() => {
            this.setState({
              isShowUser: false,
            });
          }}
          onOk={this.selectUser}
          saveDistance={0}
          destroyOnClose
        >
          <Row gutter={{ ...rowGutterPxLayout }} style={{marginBottom:'24px'}}>
            <Col {...colSpanLayout}>
              <Input
                type="text"
                autocomplete="off"
                placeholder="名称"
                onChange={e => {
                  this.setState({
                    likeProductName: e.target.value
                  });
                }}
                onPressEnter={() => {
                  this.getSelectUser(model.jumpType,this.state.likeProductName);
                }}
              />
            </Col>
            <Col {...colSpanLayout}>
              <Button
                type="primary"
                icon="search"
                onClick={() => {
                  this.getSelectUser(model.jumpType,this.state.likeProductName);
                }}
              >
                <FormattedMessage id="ours.curd.list.base-form.search" defaultMessage="查询" />
              </Button>
            </Col>
          </Row>
          <div className="content-wrap">
            <Table
              rowSelection={rowSelection}
              columns={this.state.allUserColumns}
              dataSource={this.state.allUserList}
              size="small"
            />
          </div>
        </Modal>
      </Form>
    );
  }
}

/* eslint-disable no-class-assign */
//无更多的绑定， 请用 @Form.create() 注解替换
EditForm = Form.create({})(EditForm);
